/************************************************************************
 *				SRLOS Team CopyRight
 *@file		comm.c
 *@author	bloceanc
 *@date		7/15/2010
 *@note		common system tools and other common operations
 *			1000level nested interrupt supported
 ************************************************************************/

static unsigned int int_state;

/*
 *	module initialize.
 *		we use 0x00000020 - 0x00001000 as the cpsr state stack. to save state when disable interrupt
 *	and restor the state from this stack!
 *		so, this nest about 1000level, nested interrupt supported!
 */
void comm_global_critical_section_init(void)
{
	int_state = 0x1000;
}

/** MUST DO NOT CHAHGE THE ORDER OF THE ASSEMBER INSTRUMENTS FOLLOW! */

/*
 *	Enter system global critical section.(save interrupt state and disable interrupt)
 *		1000 nested supported!
 */
void comm_global_critical_section_enter(void)
{
	// must disable interrupt first!, if we write them torgether, gcc will change the order of instructions!
	__asm__(	\
	"stmfd sp!, {r0,r1,r3}\n\t"	\
	"mrs r0, cpsr\n\t"	\
	"mov r1, r0\n\t"		\
	"orr r0, r0, #0xc0\n\t"	\
	"msr cpsr_c, r0\n\t"	\
	:::"r1","r0","memory","cc");// we must used "memory" to tell gcc need reload value of int_state.指令屏障！
	
	__asm__(	\
	"mov r3, %1\n\t"		\
	"stmfd r3!, {r1}\n\t"	\
	"mov %0, r3\n\t"		\
	"ldmfd sp!, {r0,r1,r3}\n\t"	\
	:"=r"(int_state):"r"(int_state):"r1","r3","memory","cc"			\
	);
}

/** MUST DO NOT CHAHGE THE ORDER OF THE ASSEMBER INSTRUMENTS FOLLOW! */

/*
 *	Leave system global critical section.(resume interrupt state)
 */
void comm_global_critical_section_leave(void)
{
	// if we write them torgether, gcc will change the order of instructions!
	__asm__(	\
	"stmfd sp!, {r0,r1}\n\t"	\
	"mov r0, %1\n\t"		\
	"ldmfd r0!,{r1}\n\t"	\
	"mov %0, r0\n\t"	\
	:"=r"(int_state):"r"(int_state):"r0","r1","memory","cc"			\
	);
	
	__asm__(	\
	"msr cpsr_c, r1\n\t"	\
	"ldmfd sp!, {r0,r1}\n\t"	\
	:::"r0","r1","memory","cc"	\
	);
}

/*
 * system faital error
 */
void system_faital_error(char *error_message)
{

}

